package net.homeip.mmhg.dao;

import java.util.Collection;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import net.homeip.mmhg.domain.Event;
import net.homeip.mmhg.domain.Task;
import net.homeip.mmhg.domain.Team;

/**
 * Hibernate implementation of <code>EventDao</code>.
 *
 * @author ilya gerasimov
 */
@Repository
public class EventDaoImpl implements EventDao {

	private HibernateTemplate template;

	@Autowired
	public void setHibernateTemplate(SessionFactory sessionFactory) {
		this.template = new HibernateTemplate(sessionFactory);
	}
	
	@Override
	@Transactional
	public void deleteEvent(Event event) {
		template.delete(event);
	}

	@Override
	@Transactional(readOnly = true)
	public Event getEvent(int id) {
		return (Event) template.get(Event.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public Collection<Event> getEvents() {
		return template.findByCriteria(DetachedCriteria.forClass(Event.class));
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public Collection<Event> getEvents(Team team) {
		return template.findByCriteria(DetachedCriteria.forClass(Event.class)
													   .add(Expression.eq("team", team)));
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public Collection<Event> getEvents(Team team, Task task) {
		return template.findByCriteria(DetachedCriteria.forClass(Event.class)
		   											   .add(Expression.eq("team", team))
		   											   .add(Expression.eq("task", task)));
	}

	@Override
	@Transactional
	public void storeEvent(Event event) {
		template.saveOrUpdate(event);
	}

}
